package com.ouc.pampas;

import com.google.common.io.Files;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class LocalFileLoader implements FileLoader {
	private static final Logger log = LoggerFactory.getLogger(LocalFileLoader.class);

	public FileLoader.Resp load(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return FileLoader.Resp.NOT_FOUND;
		}
		FileLoader.Resp resp = new FileLoader.Resp();
		resp.setSign(String.valueOf(file.lastModified()));
		try {
			resp.setContext(Files.toByteArray(file));
		} catch (Exception e) {
			log.error("error when load local file: {}", path, e);
			return FileLoader.Resp.NOT_FOUND;
		}
		return resp;
	}

	public FileLoader.Resp load(String path, String sign) {
		File file = new File(path);
		if (!file.exists()) {
			return FileLoader.Resp.NOT_FOUND;
		}
		if (file.lastModified() == Long.valueOf(sign).longValue()) {
			return FileLoader.Resp.NOT_MODIFIED;
		}
		FileLoader.Resp resp = new FileLoader.Resp();
		resp.setSign(String.valueOf(file.lastModified()));
		try {
			resp.setContext(Files.toByteArray(file));
		} catch (Exception e) {
			log.error("error when load local file: {}", path, e);
			return FileLoader.Resp.NOT_FOUND;
		}
		return resp;
	}
}
